package com.lanxin.xxform.aspects;

import java.util.LinkedHashMap;
import java.util.Map;

import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

import com.lanxin.xxform.aspects.exceptions.ParamException;
import com.lanxin.xxform.aspects.exceptions.ServiceException;
import com.lanxin.xxform.aspects.exceptions.SessionException;
import com.lanxin.xxform.tools.JetDate;

/**
 * 通用错误处理器
 */
@ControllerAdvice
public class ErrorProcess {
    
    int RES_FAIL    = 101;  //通用错误
    int RES_RUNF    = 102;  //运行时错误
    int RES_PARAMF  = 103;  //参数错误
    int RES_TOKENF  = 104;  //令牌错误
    int RES_SERVEF  = 106;  //业务逻辑错误

    /**
     * 通用异常处理
     * @param e
     * @return
     */
    @ExceptionHandler(Exception.class)
    @ResponseBody
    Map<String, Object> universalException(Exception e) {
        return buildResponse(RES_FAIL, "错误：" + e.getMessage());
    }

    /**
     * 运行时异常处理
     * @param e
     * @return
     */
    @ExceptionHandler(RuntimeException.class)
    @ResponseBody
    Map<String, Object> runtimeException(RuntimeException e) {
        //e.printStackTrace();
        String result = e.getMessage();
        if (result.length() > 1000) {
            result = result.substring(0, 1000);
        }
        //logsService.warning("服务运行异常", result, "", "");
        return buildResponse(RES_RUNF, "运行异常：" + e.getMessage());
    }

    /**
     * 会话异常处理
     * @return
     */
    @ExceptionHandler(SessionException.class)
    String sessionException(SessionException e) {
        return "redirect:/";
    }

    /**
     * 参数异常
     * @param e
     * @return
     */
    @ExceptionHandler(ParamException.class)
    @ResponseBody
    Map<String, Object> paramException(ParamException e) {
        if (e.getMessage() != null) {
            return buildResponse(RES_PARAMF, "参数错误：" + e.getMessage());
        }
        return buildResponse(RES_PARAMF, "参数错误或者缺失");
    }

    /**
     * 业务异常处理
     * @param e
     * @return
     */
    @ExceptionHandler(ServiceException.class)
    @ResponseBody
    Map<String, Object> serviceException(ServiceException e) {
        return buildResponse(RES_SERVEF, e.getMessage());
    }

    /**
     * 构建报错报文
     * @param code
     * @param msg
     * @return
     */
    private Map<String, Object> buildResponse(int code, String msg) {
        LinkedHashMap<String, Object> map = new LinkedHashMap<>();
        map.put("code", code);
        map.put("error", msg);
        map.put("date", JetDate.dateNow("yyyy-MM-dd HH:mm:ss"));
        return map;
    }

}
